package com.yf.service.course.impl;

import com.yf.dao.course.ActivityDao;
import com.yf.dao.course.SignUpDao;
import com.yf.entity.course.ActivityEntity;
import com.yf.entity.course.SignUpEntity;
import com.yf.enums.PayStatusEnum;
import com.yf.service.course.SignUpService;
import com.yf.service.impl.BaseServiceImpl;
import com.yf.utils.CommonUtil;
import com.yf.vo.OrderPayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 报名Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Thu Nov 15 14:26:02 CST 2018
 */
@Service
public class SignUpServiceImpl extends BaseServiceImpl<SignUpEntity> implements SignUpService {
    @Autowired
    private SignUpDao signUpDao;

    @Autowired
    private ActivityDao activityDao;



    /**内部方法**/


    /**外部方法实现**/
    @Override
    public OrderPayVO signUp(Long userId,Long activityId,String phone) {

        ActivityEntity activityEntity = activityDao.get(activityId);

        //生成编号
        String orderNo = CommonUtil.createNo();

        SignUpEntity signUpEntity = new SignUpEntity(userId,activityId,activityEntity.getPrice(),PayStatusEnum.UNPAID.getState(),new Date(),phone,orderNo);

        if(new BigDecimal(0).compareTo(activityEntity.getPrice())==0){
            signUpEntity.setPayStatus(PayStatusEnum.PAID.getState());
        }

        signUpDao.save(signUpEntity);

        String orderInfo = "欢迎报名"+activityEntity.getName();

        return new OrderPayVO(orderNo,orderInfo,activityEntity.getPrice());
    }

    public void updatePayStatus(String orderNo, String totalFee) {
        SignUpEntity SignUpEntity = signUpDao.getByOrderNo(orderNo);
        Integer payStatus = 0;  //支付状态

        //判断金额
        if(new BigDecimal(totalFee).compareTo(SignUpEntity.getPrice().multiply(new BigDecimal(100)))!=0){
            payStatus=PayStatusEnum.ERROR.getState();

        }else if(!PayStatusEnum.PAID.getState().equals(SignUpEntity.getPayStatus())){  //改变支付状态
            payStatus=PayStatusEnum.PAID.getState();
        }

        SignUpEntity.setPayStatus(payStatus);

        signUpDao.update(SignUpEntity);

    }
}
